package org.jash.shop2202.shop

import android.content.Context
import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.google.android.material.search.SearchView
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import org.jash.shop2202.BR
import org.jash.shop2202.R
import org.jash.shop2202.databinding.FragmentHomeBinding
import org.jash.shop2202.databinding.ItemKeywordBinding
import org.jash.shop2202.entity.BannerEntity
import org.jash.shop2202.entity.Goods
import org.jash.shop2202.mvvm.BaseFragment
import org.jash.shop2202.mvvm.BaseViewModel
import org.jash.shop2202.utils.CommonAdapter
import org.jash.shop2202.utils.StoreUtils
import org.jash.shop2202.utils.logging


@Route(path = "/shop/home")
@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    private val adapter by lazy { CommonAdapter<Goods>({R.layout.item_goods to BR.goods}) }
    private val searchAdapter by lazy { CommonAdapter<Goods>({R.layout.item_goods to BR.goods}) }
    private lateinit var keyword:String
    private var page = 1;
    private val size = 10;
    override fun initData() {
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                adapter.clear()
            }
            adapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.bannerLiveData.observe(viewLifecycleOwner) {
            binding.banner.update(it.map(BannerEntity::imagePath), it.map(BannerEntity::desc))
        }
        viewModel.searchLiveData.observe(viewLifecycleOwner) {
            searchAdapter.clear()
            searchAdapter += it
            if (it.isNotEmpty()) {
                StoreUtils.getUtils().put("keywords", StoreUtils.getUtils().getStringSet("keywords", setOf()) + keyword)
            }
            binding.keywords.isVisible = it.isEmpty()
        }
        viewModel.loadGoods(page, size)
        viewModel.loadBanner()
    }

    override fun initView() {
        binding.recycler.adapter = adapter
        binding.searchRv.adapter = searchAdapter
        binding.banner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView?.let {
                    Glide.with(it)
                        .load(path)
                        .into(it)
                }
            }
        })
            .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE)
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.loadGoods(page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.loadGoods(++page, size)
        }
        binding.search.addTransitionListener { _, _, newState ->
            if (newState == SearchView.TransitionState.SHOWING) {
                searchAdapter.clear()
                binding.keywords.isVisible = true
                binding.keywords.removeAllViews()
                val keywords = StoreUtils.getUtils().getStringSet("keywords", setOf())
                keywords.forEach {
                    val b = ItemKeywordBinding.inflate(layoutInflater, binding.keywords, true)
                    b.main.text = it
                    b.main.setOnClickListener { _ ->
                        keyword = it
                        viewModel.search(keyword)
                    }
                }
            }

        }
        binding.search.editText.setOnEditorActionListener { v, _, event ->
            if (event?.action == KeyEvent.ACTION_UP) {
                keyword = v.text.toString()
                viewModel.search(keyword)
            }
            true
        }
    }

    override fun error(throwable: Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }

}